# == Schema Information
# Schema version: 36
#
# Table name: sections
#
#  id                  :integer       not null, primary key
#  name                :string(255)   not null
#  section_description :string(255)   
#  issue_id            :integer       not null
#  created_at          :datetime      not null
#  updated_at          :datetime      not null
#

# A Section represents a group of similar articles, like Sports or Arts.
#
# A Section has many articles (look at the articles documentation)
# and belongs to an Issue
#
class Section < ActiveRecord::Base
    belongs_to :issue
    has_and_belongs_to_many :articles

    validates_presence_of :name
    #Only one section with the same name per issue
    validates_uniqueness_of :name, :scope=>"issue_id", :message=>":  already exists for a section in this issue"
    validates_length_of :name, :minimum=>3

    #Look for the sections in an issue
    #TODO: Change the query here is too unsafe!
    def self.find_by_issue (issue_id)
     self.find(:all, :conditions => ["issue_id ~* ?", issue_id] , :order=>"name ASC")
    end
    
    def self.find_by_issue_and_name (issue, name)
      issue_id = issue.id
      
      s = self.find(:first, :conditions => ["issue_id ~* ? AND name = ? ", issue_id, name] )
 
      
      
    end

    #Escaping html
    def before_save
      ERB::Util.h(self.name)
      ERB::Util.h(self.section_description)
    end
    
    # TODO: Destrouy all the references in articles_sections
    def after_destroy
      
    end
    
    #Prevent deletion unless it contains no articles
    def before_destroy
      if self.articles.count >0
        raise "This section already has articles associated delete them first"
      end
    end
    
end
